<?php
/**
 * Popup Status Multiple Assignment
 * To set a status for a group of contact
 *
 * @author Xavier VILAIN
 * @package Hive\Ressource
 * @license #license-hive#
 *  
 */
/* @var $contact Hive\Ressource */
use Doctrine\DBAL\Types\Type;
use Hive\Ressource;
use Fox\Popup;
use Fox\Html\DropList;
use Fox\Html\Screen;
use Fox\Generator;
use Fox\Html\Input;
use Doctrine\DBAL\Connection;
use Fox\Dao\SqlFragment;

$xview = Xview::instance();
// Selected Contacts
$checkedContacts = $xview->val('checked',$xview->val('rids'));
if(!empty($checkedContacts)) {
	$contactIds = json_decode($checkedContacts,true);
	$checkedContacts = str_replace('"',"'",$checkedContacts);
} 
$jsonRids = addslashes($checkedContacts);

if(!empty($jsonRids)) {
	$nbContact = count($contactIds);
} else {
	$nbContact = 0;
}

$screen = new Screen('sStatus','update',null,true,Generator::submit('#sSearchRessource'));
// Availble Status
$status = Hive\Contact\Status::loadActives();
$screen->block()
		->add(new DropList('status'))
		->options($status,'status',Generator::call('label'));

$screen->block()->add(new Input('rids',false,$checkedContacts))
			->hidden(true);
if(!Fox\Authorization\Manager::check(Hive\Ressource::AUTH_STATUS_CAN_VALID)) {
	// Trig An Error : User is not allowed to do this
	$screen->input(false,true);
}
	
if($screen->submitted())
{
	
	$inputs = $screen->get();
	$ressourceIds = json_decode(str_replace("'",'"',$inputs['rids']));
	$finder = new Ressource();
	$fragments[] = new SqlFragment('ressource_id IN (?) AND status NOT LIKE ? ',
						array($ressourceIds,$inputs['status']),
						array(Connection::PARAM_INT_ARRAY,Type::STRING)
						);
	$contacts = $finder->find(Fox\Dao\SqlFragment::combine($fragments));
	try {
		foreach($contacts as $contact) {
			$contact->status = $inputs['status'];
			$contact->prepareUpdate(Ressource::CHANGE_STATUS_ONLY);
			$contact->update();
		}
		Fox\Message::Success(Msg(Hive::BUNDLE,Hive::STATUS_UPDATED));
		echo $xview->messages(false,true);
		exit;
	} catch(Fox\Object\Exception\Save $e) {
		Fox\Message::Error($e);
	}
	echo $xview->messages(false,false);
}
else
{
	
	Fox\Message::Warning(Msg(Hive::BUNDLE,Hive::UPDATE_STATUS_WARNING,$nbContact));
	$popup = new Popup('pStatus',Msg(Hive::BUNDLE,Hive::BUT_UPDATE_STATUS),$screen);
	echo $popup->display();
}